<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

include('includes/Admin.Core.php');

CheckAccess('managetemplate');


PrintHeader('模板管理');

$action = ForceIncomingString('action', 'displayimages');
$folderpath = ForceIncomingString('folderpath', '../templates/');

echo '<script type="text/javascript">
function yiru(t, tw, th, e){    
	var ei = $("t_big_image");
	if(!ei){
		var thisstyle = "";
		var thisw = null;
		var thish = null;
		if (tw > 380){
			thisstyle = "width=380px";
			thisw = 380;
			thish = parseInt(380 * th / tw);
		}else if (th > 380){
			thisstyle = "height=380px";
			thisw = parseInt(380 * tw / th);
			thish = 380;
		}else if (th < 160 && tw <= th){
			thisstyle = "height=160px";
			thisw = parseInt(160 * tw / th);
			thish = 160;
		}else if (tw < 160 && tw >= th){
			thisstyle = "width=160px";
			thisw = 160;
			thish = parseInt(160 * th / tw);
		}else{
			thisstyle = "width=" + tw + " height=" + th;
			thisw = tw;
			thish = th;
		}
		var d = document.createElement("DIV");
		d.id = "t_big_image";
		d.style.position = "absolute";
		d.style.zindex = "88888";
		d.style.border = "1px solid #B2B2B2";
		d.style.padding = "6px";
		ei = document.body.appendChild(d);
		ei.innerHTML = "<img src=\"" + t.src + "\"  " + thisstyle + ">";
		ei.style.display = "";
	}
	var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);         
	var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);

	if(ei.offsetHeight > (e.clientY-10)){
		ei.style.top  = scrollTop + e.clientY + 10 + "px";
	}else{
		ei.style.top  = scrollTop + e.clientY - ei.offsetHeight - 10 + "px";
	}
	
	if(ei.offsetWidth > (e.clientX-10)){
		ei.style.left  = scrollLeft + e.clientX + 10 + "px";
	}else{
		ei.style.left = scrollLeft + e.clientX - ei.offsetWidth - 10 + "px";
	}
}

function yichu(){
	var ei = $("t_big_image");
	if(ei){
		document.body.removeChild(ei);
	}
}
</script>';

// ############################# GET TEMPLATES FOLDERS #############################

function DisplayFileDetails($file, $tdstyle = '')
{
  global $folderpath, $weenurl;

  $filepath = $folderpath . $file;

  $imageextensions = array('jpeg', '.gif', '.jpg', '.bmp', '.png');
  $fileextensions = array('html', '.css', '.htm', '.php', '.txt', '.asp', '.jsp', '.tpl', '.xml', '.swf',  '.flv');
  
  $extension = strtolower(substr($file, -4));
  $extension2 = strtolower(substr($file, -3));

  if(in_array($extension, $imageextensions))
  {
    $maxwidth  = 80;
    $maxheight = 80;

    if($imagesize = @getimagesize($filepath))
    {
      list($width, $height, $type, $attr) = $imagesize;

      $scale = min($maxwidth/$width, $maxheight/$height);
      $newwidth  = ($scale < 1) ? floor($scale * $width)  : $width;
      $newheight = ($scale < 1) ? floor($scale * $height) : $height;

      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="80" height="80" align="center" style="padding-right: 15px;">
                <a href="' . $filepath . '" target="_blank"><img border="0" src="' . $filepath . '" width="' . $newwidth . '" height="' . $newheight . '"  onMouseMove="yiru(this, '.$width.', '.$height.', event);" onMouseOut="yichu(this);" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b> (' .DisplayFilesize(filesize($filepath)) . ')<br />
                宽:  ' . $width . ' px<br />
                高: ' . $height . ' px<br /><br />
                <a href="admin.templates.php?action=deleteimage&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">删除图片</a>
              </td>
            </tr>
            </table>';
    }
  }
  else if(in_array($extension, $fileextensions) || $extension2 == '.js')
  {
      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="10" valign="top" style="padding-right: 15px;">
                <a href="admin.templates.php?action=edittemplatefile&folderpath=' . $folderpath . '&imagepath=' . $filepath . '"><img border="0" src="templates/images/editablefile' . Iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b> (' .DisplayFilesize(filesize($filepath)) . ')<br /><br />
                <a href="admin.templates.php?action=deleteimage&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">删除文件</a><br /><br />
				<a href="admin.templates.php?action=edittemplatefile&folderpath=' . $folderpath . '&imagepath=' . $filepath . '">编辑文件</a>
              </td>
            </tr>
            </table>';
  
  }
  else
  {
    if($file == '..')
    {
      if(substr($folderpath, -10) == 'templates/')
      {
        echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="10" valign="top" style="padding-right: 15px;">
                  <img border="0" src="templates/images/folderforbidden' . Iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" />
                </td>
                <td valign="top">
                  <br />
                  当前是模板根文件夹.
                </td>
              </tr>
              </table>';
      }
      else
      {
        $tmp_folderpath = explode('/', substr($folderpath, 0, -1));
        echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td width="10" valign="top" style="padding-right: 15px;">
                  <a href="admin.templates.php?folderpath=' . str_replace(end($tmp_folderpath), '', substr($folderpath, 0, -1))  . '"><img border="0" src="templates/images/folderup' . Iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>上层文件夹</b><br /><br />
                <a href="admin.templates.php?folderpath=' . str_replace(end($tmp_folderpath), '', substr($folderpath, 0, -1))  . '">返回上层文件夹</a>
              </td>
              </tr>
              </table>';
      }
    }
    else if(is_dir($filepath))
    {
      echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td width="10" valign="top" style="padding-right: 15px;">
                <a href="admin.templates.php?folderpath=' . $filepath . '/"><img border="0" src="templates/images/folder' . Iif($tdstyle == 'tdrow3', '1' , '2') . '.gif" /></a>
              </td>
              <td valign="top">
                <b>' . $file . '</b><br /><br />
                <a href="admin.templates.php?folderpath=' . $filepath . '/">打开文件夹</a>
              </td>
            </tr>
            </table>';
    }
  }

}

// ############################### UpdateTemplateCache ################################
function UpdateTemplateCache(){
	require_once (BASEPATH . 'library/smarty/libs/Smarty.class.php');
	$smarty = new Smarty;
	$smarty->compile_dir = BASEPATH.'library/smarty/templates_c/';
	$smarty->clear_compiled_tpl();

	PrintRedirect('admin.templates.php', 1);
}

// ############################### UpdateDefaultTemplate ################################
function UpdateDefaultTemplate(){
	global $DB, $mainsettings;

	$siteDefaultTemplate = ForceIncomingString('siteDefaultTemplate');

	if($mainsettings['siteDefaultTemplate'] != $siteDefaultTemplate){
		require_once (BASEPATH . 'library/smarty/libs/Smarty.class.php');
		$smarty = new Smarty;
		$smarty->compile_dir = BASEPATH.'library/smarty/templates_c/';
		$smarty->clear_compiled_tpl();
	}
	$DB->query("UPDATE " . TABLE_PREFIX . "mainsettings SET value = '".$siteDefaultTemplate."' WHERE varname = 'siteDefaultTemplate'");

	PrintRedirect('admin.templates.php', 1);
}

// ############################### UPLOAD IMAGE ################################

function UploadImage()
{
  global $folderpath;

  $image     = $_FILES['image'];
  $imagesdir = dirname(__FILE__) . '/' .  $folderpath;

  $valid_image_extensions = array('gif', 'jpg', 'peg', 'bmp', 'tml', 'htm', 'php', 'css', 'txt', 'asp', 'swf', 'flv', 'jsp', '.js', 'xml', 'tpl',  'png');

  if($image['size'] == 0){
		$errors[] = '请选择要上传的文件!';
  }else if(!in_array(strtolower(substr($image['name'], -3)), $valid_image_extensions)){
		$errors[] = '不允许的文件类型!';
  }elseif (!IsUploadedFile($image['tmp_name']) || !($image['tmp_name'] != 'none' && $image['tmp_name'] && $image['name']) ){
		$errors[] ='Possible file upload attack!';
  }elseif (file_exists($imagesdir . $image['name'])){
		$errors[] = '目标文件夹内存在同名的文件, 请先删除原文件再上传!';
  }else{

		@chmod($imagesdir, 0777);

		if((function_exists('move_uploaded_file') AND @move_uploaded_file($image['tmp_name'], $imagesdir . $image['name'])) OR @copy($image['tmp_name'], $imagesdir . $image['name'])){
			@chmod($imagesdir . $image['name'], 0777);
			@unlink($image['tmp_name']);
		}else{
			$errors[] = '文件夹 "' . substr($folderpath, 1) . '" 不可写!<br />注: 将文件夹 "' . substr($folderpath, 1) . '" 的属性改为: 777.';
		}
  }

  if(isset($errors))
  {
    PrintErrors($errors, '上传错误');
    DisplayImages();
  }
  else
  {
    DisplayImages($image['name']);
  }
}

// ########################### DISPLAY IMAGE DETAILS ###########################

function DisplayImageDetails($imagename, $imagepath, $extratext = '')
{
	
  $maxwidth  = 80;
  $maxheight = 80;

   if($imagesize = @getimagesize($imagepath))
    {
 
	  list($width, $height, $type, $attr) = $imagesize;
	
	  $scale = min($maxwidth/$width, $maxheight/$height);
	
	  if($scale < 1)
	  {
		$newwidth = floor($scale * $width);
		$newheight = floor($scale * $height);
	  }
	  else
	  {
		$newwidth = $width;
		$newheight = $height;
	  }
	
	  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<tr>
			  <td width="10" valign="top" style="padding-right: 15px;">
				<a href="' . $imagepath . '" target="_blank"><img src="' . $imagepath . '" width="' . $newwidth . '" height="' . $newheight . '"  onMouseMove="yiru(this, '.$width.', '.$height.', event);" onMouseOut="yichu(this);" /></a>
			  </td>
			  <td valign="top">
				<b>' . $imagename . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' .DisplayFilesize(filesize($imagepath)) . '</b><br /><br />
				宽:  ' . $width . ' 像素<br />
				高: ' . $height . ' 像素' . Iif(strlen($extratext), '<br /><br />' . $extratext, '') . '
			  </td>
			</tr>
			</table>';
  
  }else{
  
	  echo '<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<tr>
			  <td valign="middle" style="padding-right: 15px;">
				<b>' . $imagename . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' .DisplayFilesize(filesize($imagepath)) . '</b><br /><br />
				非图片文件, 大小: ' .DisplayFilesize(filesize($imagepath)) . Iif(strlen($extratext), '<br /><br />' . $extratext, '') . '
			  </td>
			</tr>
			</table>';
  }
}

// ############################### DELETE IMAGE ################################

function DeleteImage()
{
  global $folderpath;

  $imagepath = ForceIncomingString('imagepath');

  $deleteimage = isset($_POST['deleteimage']) ? $_POST['deleteimage'] : 'Confirm Delete';


  if($deleteimage == ' 确定删除 ')
  {
    if(@unlink($imagepath))
    {
      PrintRedirect('admin.templates.php?action=displayimages&folderpath=' . $folderpath, 1);
    }
    else
    {
      $errors[] = '无法删除文件!';
      PrintErrors($errors, '删除失败');
      $deleteimage = 'Confirm Delete';
    }
  }
  else if($deleteimage == ' 取消 ')
  {
    PrintRedirect('admin.templates.php?action=displayimages&folderpath=' . $folderpath, 1);
  }

  if($deleteimage == 'Confirm Delete')
  {
    PrintSection('删除文件');
    echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1" colspan="2">确认删除</td>
          </tr>
          <tr>
            <td class="tdrow2" width="70%" valign="top">';

    $extratext = '<b>确定删除此文件吗?</b>';
	
    DisplayImageDetails(substr($imagepath, 1), $imagepath, $extratext);

    echo '</td>
            <td class="tdrow3" valign="top">
              <form method="post" action="admin.templates.php">
              <input type="hidden" name="action" value="deleteimage" />
              <input type="hidden" name="folderpath" value="' . $folderpath . '" />
              <input type="hidden" name="imagepath" value="' . $imagepath . '" />
              <input type="submit" name="deleteimage" value=" 确定删除 " />&nbsp;&nbsp;
              <input type="submit" value=" 取消 " onclick="window.location=\'admin.templates.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" />
              </form>
            </td>
          </tr>
          </table>';
    EndSection();
  }

}


// ############################### EDIT FILE ################################

function EditTemplateFile()
{
  global $folderpath;

  $imagepath = ForceIncomingString('imagepath');

  $savefile = isset($_POST['savefile']) ? $_POST['savefile'] : 'Confirm Edit';

  if($savefile == ' 保存更新 ')
  {
	if (is_writable($imagepath)) {
		$filecontent = trim($_POST['filecontent']);
		if (get_magic_quotes_gpc()) {
			$filecontent = stripslashes($filecontent);
		}

		$fd = fopen($imagepath,'wb');
		fputs($fd,$filecontent);
	  
		PrintRedirect('admin.templates.php?action=displayimages&folderpath=' . $folderpath, 1);
	}else{
		$errors = '模板文件('.BASEURL . substr($imagepath, 3).')不可写! 请将其属性设置为: 777';
		PrintErrors($errors, '编辑模板错误');
		$savefile = 'Confirm Edit';
	}

  }
  else if($savefile == ' 取消 ')
  {
    PrintRedirect('admin.templates.php?action=displayimages&folderpath=' . $folderpath, 1);
  }

  if($savefile == 'Confirm Edit')
  {
	 if ($imagepath){ $oldfilecontent = htmlspecialchars(implode("",file($imagepath)));}
	 
    PrintSection('编辑文件');
    echo '<form method="post" action="admin.templates.php">
	       <table width="100%" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td class="tdrow1">
			<input type="hidden" name="action" value="edittemplatefile" />
              <input type="hidden" name="folderpath" value="' . $folderpath . '" />
              <input type="hidden" name="imagepath" value="' . $imagepath . '" />
              <input type="submit" name="savefile" value=" 保存更新 " onclick="return confirm(\'确定更新文件吗?\');" />&nbsp;&nbsp;
              <input type="submit" value=" 取消 " onclick="window.location=\'admin.templates.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" /></td>
          </tr>
          <tr>
            <td class="tdrow2" width="100%" valign="top">当前文件: '. BASEURL . substr($imagepath, 3) . '<BR><BR>
			<textarea rows="36" style="width: 100%;" name="filecontent" >' . $oldfilecontent . '</textarea>
          <tr>
            <td class="tdrow1">
              <input type="submit" name="savefile" value=" 保存更新 " onclick="return confirm(\'确定更新文件吗?\');" />&nbsp;&nbsp;
              <input type="submit" value=" 取消 " onclick="window.location=\'admin.templates.php?action=displayimages&folderpath=' . $folderpath . '\'; return false" /></td>
          </tr>';


    echo '</td>
          </tr>
          </table></form>';
    EndSection();
  }

}


// ############################### DISPLAY IMAGES ##############################

function DisplayImages($newimage = '')
{
  global $folderpath, $mainsettings;

  $currentpath = '<b>当前文件夹:</b> ' . BASEURL;

	PrintSection('更新缓存|切换模板');
	echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
	<tr>
	<td class="tdrow2" width="30%">当修改或编辑了前台模板文件(.tpl)后, 需要更新模板缓存:</td>
	<td class="tdrow3" width="20%">
	<form method="post" action="admin.templates.php">
	<input type="hidden" name="action" value="updatetemplatecache" />
	<input type="submit" value=" 更新缓存 " />
	</form>
	</td>
	<form method="post" action="admin.templates.php">
	<td class="tdrow2" width="30%" align="right">前台默认模板: ';
	$Templates = GetTemps();

	$Select = NewObject('Select');
	$Select->Name = 'siteDefaultTemplate';
	$Select->SelectedValue = $mainsettings['siteDefaultTemplate'];
	foreach($Templates as $val)
	{
		$Select->AddOption($val, $val);
	}

	echo $Select->Get();

	echo '</td>
	<td class="tdrow3" width="20%">
	<input type="hidden" name="action" value="updatedefaulttemplate" />
	<input type="submit" value=" 保存更新 " />
	</td>
	</form>
	</tr>
	</table>';
	EndSection();

  PrintSection('上传文件');
  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0">
			<tr>
			<td class="tdrow1"> ' . $currentpath . substr($folderpath, 3) . '</td>
			</tr>
			<tr>
			<td class="tdrow2">';
		  
	if($newimage)
	{
		echo '<font class=ohblueb>上传文件成功!</font><br /><br />';
	}

	echo '上传文件到当前文件夹:<br />
			  <form enctype="multipart/form-data" method="post" action="admin.templates.php" name="upload_form">
			  <input type="hidden" name="action" value="uploadimage" />
			  <input type="hidden" name="folderpath" value="' . $folderpath . '" />
			  <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
			  <input name="image" type="file" size="38" />
			  <input type="submit" value="上传文件" />
			  </form>
			  <br />(注: 仅可上传jpg, png, gif, bmp, htm, html, php, css, txt, asp, jsp, js, tpl, xml, swf, flv文件)</td>
			</tr>
			</table>';
  EndSection();

  PrintSection('模板文件列表');
  
  $files   = array();
  $images  = array();
  $folders = array();
  $handle  = opendir($folderpath);

  while(false !== ($file = readdir($handle)))
  {
    $extension = strtolower(substr($file, -4));
    $extension2 = strtolower(substr($file, -3));

    $fileextensions = array('jpeg', '.gif', '.jpg', '.bmp', '.png', 'html', '.css', '.htm', '.php', '.txt', '.asp', '.jsp', '.tpl', '.xml', '.swf', '.flv');

    if(in_array($extension, $fileextensions) || $extension2 == '.js')
    {
      $images[]  = $file;
    }
    else if($file != '.' AND is_dir($folderpath . $file))
    {
      $folders[] = $file;
    }
  }

  // now sort both images and folders
  @sort($images);
  @sort($folders);

  $files = @array_merge($folders, $images);

  $columncount = 0;
  $tdstyle = 'tdrow3';


  echo '<table width="100%" border="0" cellpadding="5" cellspacing="0"><tr>
          <td class="tdrow1" colspan="3"> ' . $currentpath . substr($folderpath, 3) . '</td>
        </tr>';

  for($i = 0; $i < count($files); $i++)
  {
    $columncount++;
    
    if($columncount == 1)
    {
      echo '<tr>';
	  $tdstyle = ($tdstyle == 'tdrow3') ? 'tdrow2' : 'tdrow3';
    }

	echo '<td width="33%" class="' . $tdstyle . '">';

    DisplayFileDetails($files[$i], $tdstyle);

    echo '</td>';

    if($columncount == 3)
    {
      echo '</tr>';

      $columncount = 0;

    }
  }

  closedir($handle);

  if($columncount != 0 && $columncount != 3)
  {
    while($columncount < 3)
    {
      $columncount++;
      echo '<td class="' . $tdstyle . '">&nbsp;</td>';
    }
    echo '</tr>';
  }

  echo '</table>';

  EndSection();

  
}


// ############################## SELECT FUNCTION ##############################

switch($action)
{
	case 'uploadimage':
		UploadImage();
	break;

	case 'updatetemplatecache':
		UpdateTemplateCache();
	break;

	case 'deleteimage':
		DeleteImage();
	break;

	case 'edittemplatefile':
		EditTemplateFile();
	break;

	case 'displayimages':
		DisplayImages();
	break;

	case 'updatedefaulttemplate':
		UpdateDefaultTemplate();
	break;
}


PrintFooter();

?>